<?PHP
#
#   FILE:  GoTo.php
#
#   Part of the Metavus digital collections platform
#   Copyright 2011-2021 Edward Almasy and Internet Scout Research Group
#   http://metavus.net
#

use Metavus\MetadataSchema;
use Metavus\Record;
use Metavus\User;
use ScoutLib\ApplicationFramework;

# request that this page not be indexed by search engines
$GLOBALS["AF"]->addMetaTag(["robots" => "noindex"]);

# if resource ID was specified
if (isset($_GET["ID"])) {
    # grab resource ID
    $ResourceId = $_GET["ID"];

    # if resource ID is valid
    if (Record::itemExists($ResourceId)) {
        # if metadata field was specified
        $Resource = new Record($ResourceId);
        if (isset($_GET["MF"])) {
            # if specified metadata field is valid
            if ($Resource->getSchema()->fieldExists($_GET["MF"])) {
                # use specified metadata field
                $FieldId = $_GET["MF"];
            }
        } else {
            # if there is a standard URL field for resource
            $StdUrlFieldId = $Resource->getSchema()->stdNameToFieldMapping("Url");
            if ($StdUrlFieldId !== null) {
                # use standard URL field
                $FieldId = $StdUrlFieldId;
            }
        }

        # if we have a metadata field ID
        if (isset($FieldId)) {
            # if URL field was specified and user has permission to view it
            $Field = $Resource->getSchema()->getField($FieldId);
            if (($Field->type() == MetadataSchema::MDFTYPE_URL)
                    && ($Resource->userCanViewField(User::getCurrentUser(), $Field))) {
                # load URL to go to
                $Url = $Resource->get($Field);

                # allow plugins to modify the value
                $SignalResult = $GLOBALS["AF"]->signalEvent(
                    "EVENT_FIELD_DISPLAY_FILTER",
                    array(
                        "Field" => $Field,
                        "Resource" => $Resource,
                        "Value" => $Url
                    )
                );
                $Url = $SignalResult["Value"];

                # don't use URLs that are definitely invalid
                if (filter_var($Url, FILTER_VALIDATE_URL) === false) {
                    unset($Url);
                }
            }
        }
    }
}

# if we found URL to go to
if (isset($Url) && isset($Resource) && isset($Field)) {
    # signal URL click event
    $GLOBALS["AF"]->signalEvent("EVENT_URL_FIELD_CLICK", array(
        "ResourceId" => $Resource->id(),
        "FieldId" => $Field->id()
    ));

    # go to page specified by URL
    $GLOBALS["AF"]->setJumpToPage($Url);
} else {
    # return to calling page
    $GLOBALS["AF"]->setJumpToPage(
        isset($_SERVER["HTTP_REFERER"]) ?
            $_SERVER["HTTP_REFERER"] :
        ApplicationFramework::baseUrl()."index.php"
    );
}
